package br.cin.stadium.middleware.network;

import br.cin.stadium.middleware.marshall.MarshallOutputStream;

/**
 * @author Jorge, Fabiano, Rafael, Vando
 * 
 */
public class DataOutputStream implements MarshallOutputStream {

	private byte[] data = null;

	private static byte INT_SIZE = 4;
	
	private BufferStream stream;

	public DataOutputStream() {
		data = new byte[0];
	}

	public DataOutputStream(BufferStream stream) {
		this.stream = stream;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * br.cin.stadium.middleware.marshall.MarshallOutputStream#writeUTF(java
	 * .lang.String)
	 */
	public void writeUTF(String s) {
		this.writeInt(s.length());

		byte[] bytes = new byte[s.length()];
		for (int i = 0; i < s.length(); i++) {
			bytes[i] = (byte) s.charAt(i);
		}
		write(bytes);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * br.cin.stadium.middleware.marshall.MarshallOutputStream#writeInt(int)
	 */
	public void writeInt(int i) {
		byte[] bytes = new byte[INT_SIZE];
		bytes[0] = (byte) (i & 0xFF);
		bytes[1] = (byte) ((i >> 8) & 0xFF);
		bytes[2] = (byte) ((i >> 16) & 0xFF);
		bytes[3] = (byte) ((i >> 24) & 0xFF);

		this.write(bytes);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * br.cin.stadium.middleware.marshall.MarshallOutputStream#write(byte[])
	 */
	public void write(byte[] bytes) {
		if(this.stream != null) {
			this.stream.writeBytes(bytes);

		} else {
			byte[] temp = new byte[data.length + bytes.length];
			System.arraycopy(data, 0, temp, 0, data.length);
			System.arraycopy(bytes, 0, temp, data.length, bytes.length);
			data = temp;
			
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.cin.stadium.middleware.marshall.MarshallOutputStream#write(byte)
	 */
	public void write(byte oneByte) {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.cin.stadium.middleware.marshall.MarshallOutputStream#getData()
	 */
	public byte[] getData() {
		return data;
	}
}
